package com.khanacademy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser
{	
	private static final String DEBUG_TAG = "JSONParser";
	
	// download data from url as a string
	public static String getHTTPData(String url)
	{
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		try
		{
			HttpResponse httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				InputStream inputStream = httpResponse.getEntity().getContent();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				StringBuilder stringBuilder = new StringBuilder();
				
				try
				{
					String line = "";
					while ((line = bufferedReader.readLine()) != null)
						stringBuilder.append(line + "\n");
				}
				catch (IOException e) { e.printStackTrace(); }
				finally
				{
					try { inputStream.close(); }
					catch (IOException e) {	e.printStackTrace(); }
				}
				
				inputStream.close();
				return stringBuilder.toString();
			}
		}
		catch (ClientProtocolException e) { Log.e(DEBUG_TAG, "ClientProtocolException in getHTTPData", e); }
		catch (IOException e) { Log.e(DEBUG_TAG, "IOException in getHTTPData", e); }
		
		return null;
	}

	// try to convert a string to a json array
	public static JSONArray getJSONArray(String url)
	{
		JSONArray array = null;
		String HTTPData = getHTTPData(url);
		try { array = new JSONArray(HTTPData); }
		catch (JSONException e) { Log.e(DEBUG_TAG, "JSONException in getJSONArray", e); }
		return array;
	}
	
	// try to convert a string to a json object
	public static JSONObject getJSONObject(String url)
	{
		JSONObject object = null;
		String HTTPData = getHTTPData(url);
		try { object = new JSONObject(HTTPData); }
		catch (JSONException e) { Log.e(DEBUG_TAG, "JSONException in getJSONObject", e); }
		return object;
	}
}